package cn.cfg;

import cn.scs.component.DatanodeFinder;

import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class WorkerParser {

    List<String> workList;
    private Pattern ipPattern = Pattern.compile("^(?!\\s*#)\\s*(?<ipv4>\\d+\\.\\d+\\.\\d+\\.\\d+)\\s+(?<name>\\S+)");

    public WorkerParser(String path) {
        try {
            Scanner scanner = new Scanner(new File(path));
            workList = new ArrayList<>();
            while (scanner.hasNextLine()) {
                String item = scanner.nextLine();
                workList.add(item);
            }
        } catch (FileNotFoundException fnf) {
            fnf.printStackTrace();
        }
    }
    // 获取所有worker
    public List<String> getWorkerName() {
        return this.workList;
    }
    // 解析hosts行 获取IP对
    public String getIpPair(String line) {
        Matcher result = ipPattern.matcher(line);
        if (result.find()) {
            return result.group("name") + ":" + result.group("ipv4");
        } else {
            return null;
        }
    }

    // 分析worker配置
    public Map<String, String> getWorker(String hostsPath) {
        return new DatanodeFinder(hostsPath).getDatanodeMap();
    }
    // 解析IP | 执行hosts文件分析 写好备用
    public Map<String, String> getWorker(String hostsPath, boolean host) {
        if (! new File(hostsPath).exists()) {
            System.out.println("hosts Path Wrong!");
            return null;
        }
        List<String> names = new ArrayList<>( Arrays.asList(workList.toArray(new String[0])) );    // 深度拷贝
        Map<String, String> workerInfo = new HashMap<>();
        try {
            // 对hosts 进行行解析
            Scanner scanner = new Scanner(new File(hostsPath));
            while (scanner.hasNextLine()) {
                String pairStr = getIpPair(scanner.nextLine());
                if (pairStr != null) {
                    String[] pair = pairStr.split(":");
                    if (names.contains(pair[0])) {
                        // 存在该worker 添加至 Map
                        workerInfo.put(pair[0], pair[1]);
                        // 删除 names 只承认首个发现的 IP对
                        names.remove(pair[0]);
                    }
                    // 否则什么也不做 跳过
                }
            }
            if (names.size() > 0) {
                for (String name: names) {
                    System.out.println("Slave Node: < " + name + " >\t-- Host Not Found");
                    workerInfo.put(name, null); // 推入空 k-v pair
                }
            }
            return workerInfo;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

}
